package info.niwota.web.bt;

import info.niwota.web.Debug;

import java.io.IOException;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class ServiceSearch {

	public static String findService(RemoteDevice device, UUID uuid) throws IOException, InterruptedException
			 {
		final String[] found = new String[1];
		
		final Object serviceSearchCompletedEvent = new Object();

		DiscoveryListener listener = new DiscoveryListener() {

			public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
			}

			public void inquiryCompleted(int discType) {
			}

			public void servicesDiscovered(int transID,
					ServiceRecord[] servRecord) {
				if (Debug.DEBUG) {
					System.out.println("sservicesDiscovered transID: " + transID + " len: " + servRecord.length);
				}
				
				for (int i = 0; i < servRecord.length; i++) {
					String url = servRecord[i].getConnectionURL(
							ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
					if (url == null) {
						continue;
					}
					found[0] = url;
					
					serviceSearchCompleted(transID, 0);
					
					if (Debug.DEBUG) {
						System.out.println("service found " + url);
					}
				}
			}

			public void serviceSearchCompleted(int transID, int respCode) {
				if (Debug.DEBUG) {
					System.out.println("service search completed!");
				}
				
				synchronized (serviceSearchCompletedEvent) {
					serviceSearchCompletedEvent.notifyAll();
				}
			}

		};

		UUID[] searchUuidSet = new UUID[] { uuid };
		int[] attrIDs = null;

		synchronized (serviceSearchCompletedEvent) {
			if (Debug.DEBUG) {
				System.out.println("search services on "
					+ device.getBluetoothAddress() + " "
					+ device.getFriendlyName(false));
			}
			LocalDevice.getLocalDevice().getDiscoveryAgent()
					.searchServices(attrIDs, searchUuidSet, device, listener);
			serviceSearchCompletedEvent.wait();
		}

		return found[0];
	}

}
